using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

using VistaDB.DDA;
using VistaDB.Provider;

using NSimpleDB.Service.Contract;
using NSimpleDB.Service.VistaDb.Managers;
using NSimpleDB.Service.VistaDb.QueryProcessing.Compiler;

namespace NSimpleDB.Service.VistaDb.QueryProcessing
{
    internal class QueryProcessor
    {
        private SchemaManager schemaMang;
        private DomainManager domainMang;
        private QueryCompiler qComp;


        public QueryProcessor(SchemaManager schemaMang, DomainManager domainMang)
        {
            this.schemaMang = schemaMang;
            this.domainMang = domainMang;
            this.qComp = new QueryCompiler();
        }


        public DataTable ExecuteQuery(string domainName, string query)
        {
            int idDomain = this.domainMang.GetDomainIdFromName(domainName);
            if (idDomain < 0) throw new SimpleDBException("ExecuteQuery: Unknown domain name '{0}'!", domainName);

            using (VistaDBConnection conn = new VistaDBConnection(this.schemaMang.Database))
            {
                DataTable tbResultset = new DataTable("ItemNames");

                string sqlQuery = this.qComp.CompileToSql(this.schemaMang.DomainTableNameFromId(idDomain), query);
                VistaDBDataAdapter adap = new VistaDBDataAdapter(sqlQuery, conn);
                adap.Fill(tbResultset);

                return tbResultset;
            }
        }
    }
}
